package com.leo.foodmaster.commons.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.leo.foodmaster.admin.system.entity.UserBean;
import com.leo.foodmaster.commons.util.WebUtils;
import org.apache.ibatis.reflection.MetaObject;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * <p>
 * 公共字段自动填充控制器
 * </p>
 *
 * @author ：Leo
 * @since ：2021-06-25 10:32
 */
public class FieldFillHandler implements MetaObjectHandler {
    private static final String CREATE_TIME = "createTime";
    private static final String CREATOR = "creator";
    private static final String CREATE_BY = "createBy";
    private static final String UPDATE_TIME = "updateTime";
    private static final String UPDATE_USER = "updateUser";
    private static final String UPDATE_BY = "updateBy";
    /**
     * 新增填充
     * @param metaObject 元数据
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 起始版本 3.3.0(推荐使用)
        if (metaObject.hasGetter(CREATE_TIME)) {
            this.strictInsertFill(metaObject, CREATE_TIME, LocalDateTime.class, LocalDateTime.now());
        }

        UserBean userBean = WebUtils.getUser();
        Optional.ofNullable(userBean).ifPresent(user -> {
            if(metaObject.hasGetter(CREATOR)){
                this.strictInsertFill(metaObject, CREATOR, String.class, user.getName());
            }
            if(metaObject.hasGetter(CREATE_BY)){
                this.strictInsertFill(metaObject, CREATE_BY, String.class, user.getName());
            }
        });
    }

    /**
     * 修改填充
     * @param metaObject 元数据
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        if(metaObject.hasGetter(UPDATE_TIME)){
            this.strictUpdateFill(metaObject, UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
        }

        UserBean userBean = WebUtils.getUser();
        Optional.ofNullable(userBean).ifPresent(user -> {
            if(metaObject.hasGetter(UPDATE_USER)){
                this.strictUpdateFill(metaObject, UPDATE_USER, String.class, user.getName());
            }
            if(metaObject.hasGetter(UPDATE_BY)){
                this.strictUpdateFill(metaObject, UPDATE_BY, String.class, user.getName());
            }
        });
    }
}
